﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using StairsModuleAndEdit.StairsEdit.Common;

namespace StairsModuleAndEdit.StairsEdit.Managers
{
	internal class SelectAndSearch
	{
		public SelectAndSearch(ExternalCommandData commandData)
		{
			this.m_commandData = commandData;
			this.uidoc = this.m_commandData.Application.ActiveUIDocument;
			this.document = this.m_commandData.Application.ActiveUIDocument.Document;
		}

		public bool MutiSelectStairs(string strPromt, ref List<Stairs> arStairs, ref string message)
		{
			SelectStair selectStair = new SelectStair();
			arStairs = new List<Stairs>();
			arStairs.Clear();
			try
			{
				IList<Reference> list = this.uidoc.Selection.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Element, selectStair, strPromt);
				foreach (Reference reference in list)
				{
					arStairs.Add(this.document.GetElement(reference) as Stairs);
				}
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				return false;
			}
			catch (Exception ex)
			{
				message = ex.Message;
				return false;
			}
			return true;
		}

		public bool SearchAllStairsByHit(ref List<Stairs> arStairs, ref string message)
		{
			View activeView = this.m_commandData.Application.ActiveUIDocument.ActiveView;
			IList<ViewPlan> list = null;
			ViewPlan activeView2 = null;
			List<Element> list2 = new List<Element>();
			bool allSameViewPlanByActiveView = CommonUnit.GetAllSameViewPlanByActiveView(this.m_commandData, ref list, ref activeView2);
            if (allSameViewPlanByActiveView && (activeView.ViewType == (ViewType)1 || activeView.ViewType == (ViewType)2))
			{
				this.m_commandData.Application.ActiveUIDocument.ActiveView = activeView2;
			}
			foreach (Element element in arStairs)
			{
				SearchAllStairs searchAllStairs = new SearchAllStairs(this.m_commandData, element as Stairs);
				if (!searchAllStairs.GetAllIntersectionStairs(ref list2, ref message))
				{
                    if (allSameViewPlanByActiveView && (activeView.ViewType == (ViewType)1 || activeView.ViewType == (ViewType)2))
					{
						this.m_commandData.Application.ActiveUIDocument.ActiveView = activeView;
					}
					return false;
				}
			}
            if (allSameViewPlanByActiveView && (activeView.ViewType == (ViewType)1 || activeView.ViewType == (ViewType)2))
			{
				this.m_commandData.Application.ActiveUIDocument.ActiveView = activeView;
			}
			using (List<Element>.Enumerator enumerator2 = list2.GetEnumerator())
			{
				while (enumerator2.MoveNext())
				{
					Element e = enumerator2.Current;
					if (arStairs.Find((Stairs p) => p.Id == e.Id) == null)
					{
						arStairs.Add(e as Stairs);
					}
				}
			}
			return true;
		}

		private ExternalCommandData m_commandData;

		private Document document;

		private UIDocument uidoc;
	}
}
